// 全局变量
let data = null;
let map = null;
const geocoder = new AMap.Geocoder();
const icon = {
	start: "../../../static/img/start.png",
	end: "../../../static/img/end.png",
};
// 根据ClassName/Id获取dom
function $(str) {
	if (str.startsWith('.')) {
		return document.getElementsByClassName(str.slice(1))[0]
	}
	if (str.startsWith('#')) {
		return document.getElementById(str.slice(1));
	}
	return null;
}
// 接收参数
function receiveData(str) {
	data = JSON.parse(str);
	console.log(data);
	// 初始化数据
	initContent();
	// 初始化echart
	initEchart();
	// 渲染轨迹
	initMap();
}

// 渲染数据
function initContent() {
	if (data.itemCode == 'ybcs') {
		$('.content').innerHTML = `<div class="items-box">
			<div class="item-box">
				<div class="label">
					<div class="dian"></div>
					车牌号(颜色):
				</div>
				<div class="text">${data.resData.vehCode||'-'}${data.resData.vehCode && data.resData.vehColor
				? "(" + data.resData.vehColor + ")"
				: ""}</div>
			</div>
			<div class="item-box">
				<div class="label">
					<div class="dian"></div>
					道路运输证号:
				</div>
				<div class="text">${data.resData.certNo || "-"}</div>
			</div>
			<div class="item-box">
				<div class="label">
					<div class="dian"></div>
					所属企业:
				</div>
				<div class="text">${data.resData.ownerName || "-"}</div>
			</div>
			<div class="title">一般超速详情</div>
			<div class="item-box">
				<div class="label">
					<div class="dian"></div>
					发生地点:
				</div>
				<div class="text">${data.occurAddr || "-"}</div>
			</div>
			<div class="item-box">
				<div class="label">
					<div class="dian"></div>
					发生时间:
				</div>
				<div class="text">${data.resData.occurTime || "-"}</div>
			</div>
			<div class="item-box">
				<div class="label">
					<div class="dian"></div>
					行驶速度:
				</div>
				<div class="text">${data.resData.speed || "0"}km/h</div>
			</div>
			<div class="item-box">
				<div class="label">
					<div class="dian"></div>
					默认限行速度:
				</div>
				<div class="text">${data.resData.speedLimit || "0"}km/h</div>
			</div>
			<div class="title">一般超速情况</div>
		</div>`;
	}
	if (data.itemCode == 'pljs') {
		const pos = [
			data.resData.endPos.split(","),
			data.resData.startPos.split(","),
		]
		getAddress(pos).then(res => {
			data.resData.endPos = res[0]
			data.resData.startPos = res[1]
			$('.content').innerHTML = `<div class="items-box">
				<div class="item-box">
					<div class="label">
						<div class="dian"></div>
						车牌号(颜色):
					</div>
					<div class="text">${data.resData.vehCode||'-'}${data.resData.vehCode && data.resData.vehColor
					? "(" + data.resData.vehColor + ")"
					: ""}</div>
				</div>
				<div class="item-box">
					<div class="label">
						<div class="dian"></div>
						道路运输证号:
					</div>
					<div class="text">${data.resData.certNo || "-"}</div>
				</div>
				<div class="item-box">
					<div class="label">
						<div class="dian"></div>
						所属企业:
					</div>
					<div class="text">${data.resData.ownerName || "-"}</div>
				</div>
				<div class="item-box">
					<div class="label">
						<div class="dian"></div>
						起点:
					</div>
					<div class="text">${data.loadingAddr || "-"}</div>
				</div>
				<div class="item-box">
					<div class="label">
						<div class="dian"></div>
						终点:
					</div>
					<div class="text">${data.resData.unloadingAddr || "-"}</div>
				</div>
				<div class="title">疲劳驾驶详情</div>
				<div class="item-box">
					<div class="label">
						<div class="dian"></div>
						起始时间:
					</div>
					<div class="text">${data.resData.startTime || "-"}</div>
				</div>
				<div class="item-box">
					<div class="label">
						<div class="dian"></div>
						终止时间:
					</div>
					<div class="text">${data.resData.endTime || "-"}</div>
				</div>
				<div class="item-box">
					<div class="label">
						<div class="dian"></div>
						连续驾驶时长:
					</div>
					<div class="text">${data.resData.duration || "-"}（分钟）</div>
				</div>
				<div class="item-box">
					<div class="label">
						<div class="dian"></div>
						起始位置:
					</div>
					<div class="text">${data.resData.startPos || "-"}</div>
				</div>
				<div class="item-box">
					<div class="label">
						<div class="dian"></div>
						终止位置:
					</div>
					<div class="text">${data.resData.endPos || "-"}</div>
				</div>
				<div class="title">疲劳驾驶情况</div>
			</div>`;
		})
	}
}

// 渲染echart
function initEchart() {
	let speedLimit = Number(data.resData.speedLimit) || 80;
	let echart = echarts.init($('#echart'));
	let dataZoomStart = 100 - Math.ceil(20 / data.echartList.length * 100);
	echart.setOption({
		title: {
			text: "一般超速情况",
			left: "center",
			top: 10,
			textStyle: {
				fontWeight: "normal",
				fontSize: "18",
				color: "#6C97FA",
			},
		},
		tooltip: {
			show: true,
			formatter(data) {
				return "时间：" + data.name + "<br/>速度：" + data.value;
			},
		},
		grid: {
			containLabel: true,
			left: 10,
			right: 30,
			top: 50,
			bottom: 50,
		},
		// 给折线的颜色增加条件判断
		visualMap: {
			show: false,
			pieces: [{
					gt: speedLimit, // 大于80的时候
					color: "#FD0100",
				},
				{
					gt: 0, // 大于0
					lte: speedLimit, // 小于等于80
					color: "#3862CF",
				},
			],
			seriesIndex: 0,
		},
		dataZoom: [{
				type: 'inside',
				start: dataZoomStart,
				end: 100
			},
			{
				start: dataZoomStart,
				end: 100
			}
		],
		xAxis: {
			type: "category",
			boundaryGap: false,
			name: "h",
			nameTextStyle: {
				color: "#333",
			},
			data: data.echartList.map((item) => item.gpsDatetime.slice(-8)),
			axisLabel: {
				rotate: 90,
				color: "#333",
			},
			axisLine: {
				show: true,
				lineStyle: {
					color: "#DDD",
				},
			},
			axisTick: {
				show: false,
			},
		},
		yAxis: {
			type: "value",
			name: "km/h",
			nameTextStyle: {
				color: "#333",
			},
			splitLine: {
				lineStyle: {
					type: "dashed",
				},
			},
			axisLine: {
				show: true,
				lineStyle: {
					color: "#DDD",
				},
			},
			axisLabel: {
				color: "#333",
			},
		},
		series: [{
			type: "line",
			smooth: true,
			data: data.echartList.map((item) => {
				return {
					value: item.speed,
					itemStyle: {
						color: Number(item.speed) > speedLimit ? "red" : "#3862CF",
					},
				};
			}),
			// 定义一条线在y轴刻度为80的地方
			markLine: {
				silent: true,
				lineStyle: {
					color: "#f00",
				},
				data: [{
					yAxis: speedLimit
				}],
			},
		}, ],
	});
}

// 渲染地图
function initMap() {
	if (data.trajectory.length < 2) {
		return;
	}
	AMapConvertFrom(data.trajectory)
		.then((polylinePath) => {
			return AMapGraspRoadDriving(polylinePath);
		})
		.then((polylinePath) => {
			// console.log(polylinePath);
			// 定义起始点和终点坐标
			let startPoint = polylinePath[0];
			let endPoint = polylinePath[polylinePath.length - 1];
			// 地图上添加路线
			new AMap.Polyline({
				map,
				path: polylinePath,
				strokeWeight: 8,
				strokeOpacity: 0.8,
				strokeColor: "#0091ea",
				showDir: true,
			});
			// 地图上添加起始点
			new AMap.Marker({
				map,
				position: startPoint,
				icon: new AMap.Icon({
					size: new AMap.Size(37, 51),
					image: icon.start,
					imageSize: new AMap.Size(37, 51),
				}),
				offset: new AMap.Pixel(0, -26),
				anchor: "center",
			});
			// 地图上添加终点
			new AMap.Marker({
				map,
				position: endPoint,
				icon: new AMap.Icon({
					size: new AMap.Size(37, 51),
					image: icon.end,
					imageSize: new AMap.Size(37, 51),
				}),
				offset: new AMap.Pixel(0, -26),
				anchor: "center",
			});
			map.setFitView();
		});
}

// 初始化地图
map = new AMap.Map("container", {
	resizeEnable: true,
	zoom: 15,
	showIndoorMap: false,
	center: [114.205173, 30.63413],
});

/**
 * 用于逆地理解析
 * @param {Array} locations
 */
function getAddress(locations) {
	return new Promise((resolve) => {
		let len = locations.length;
		let resIndex = 0;
		const res = [];

		for (let i = 0; i < len; i++) {
			AMap.convertFrom(locations[i], "gps", (s1, r1) => {
				if (s1 === "complete" && r1.info === "ok") {
					let converts = r1.locations.map((o) => [o.lng, o.lat]);
					// 高德坐标逆地理解析(单次最多20个)
					geocoder.getAddress(converts, (s2, r2) => {
						resIndex++;
						if (s2 === "complete" && r2.info === "OK") {
							res[i] = r2.regeocodes.map((o) => o.formattedAddress);
						} else {
							res[i] = [""];
						}
						if (resIndex == len) {
							resolve(res.flat());
						}
					});
				} else {
					res[i] = [""];
					if (resIndex == len) {
						resolve(res.flat());
					}
				}
			})
		}
	})
}

/**
 * 将其他地图服务商的坐标批量转换成高德地图经纬度坐标
 * @param {*} locations 传入经纬度数组:经度lon,纬度lat
 * @param {*} type 原始坐标类型：gps,baidu,mapbar
 * @returns Promise
 */
function AMapConvertFrom(locations, type = "gps") {
	return new Promise((resolve, reject) => {
		const pages = Math.ceil(locations.length / 500);
		let res = [];
		let resIndex = 0;
		let resState = true;
		for (let i = 0; i < pages; i++) {
			const locationsSlice = locations.slice(500 * i, 500 * (i + 1));
			const LngLat = locationsSlice.map((item) => [item.lon, item.lat]);

			AMap.convertFrom(LngLat, type, function(status, result) {
				resIndex++;
				if (result.info === "ok") {
					// console.log(locations, result.locations);
					res[i] = locationsSlice.map((item, index) => {
						item.lon = result.locations[index].lng;
						item.lat = result.locations[index].lat;
						return item;
					});
				} else {
					resState = false;
				}
				if (resIndex == pages) {
					if (resState) {
						res = res.flat();
						resolve(res);
					} else {
						reject();
					}
				}
			});

		}
	});
};

/**
 * 用于驾车轨迹的纠偏
 * @param {Array} locations 
 * [{
 *  lon:经度;
 *  lat:纬度,
 *  direction:与正北方向夹角,
 *  posSec:当前采集点的时间，单位（毫秒）
 *  v1:轨迹点的速度，单位km/h
 * }]
 * @returns Promise
 */
const graspRoad = new AMap.GraspRoad();

function AMapGraspRoadDriving(locations) {
	return new Promise((resolve, reject) => {
		let prevPoints = [];
		// 过滤重复的点位
		locations = locations.filter(item => {
			if (prevPoints.lon == item.lon && prevPoints.lat == item.lat && !prevPoints.v1) {
				return false;
			}
			prevPoints = item;
			return true;
		});
		let posSec;
		const points = locations.map((item) => {
			let tm = item.posSec / 1000;
			if (posSec) {
				tm = tm - posSec;
			} else {
				posSec = tm;
			}
			return {
				x: item.lon,
				y: item.lat,
				sp: item.v1,
				ag: item.direction,
				tm,
			};
		});
		const pages = Math.ceil(points.length / 500);
		let res = [];
		let resIndex = 0;
		let resState = true;
		for (let i = 0; i < pages; i++) {
			const pointsSlice = points.slice(500 * i, 500 * (i + 1));
			graspRoad.driving(pointsSlice, (error, result) => {
				resIndex++;
				if (!error) {
					const newPath = result.data.points;
					res[i] = newPath;
				} else {
					resState = false;
				}
				if (resIndex == pages) {
					if (resState) {
						res = res.flat();
						res = res.map((item) => {
							return new AMap.LngLat(item.x, item.y);
						});
						resolve(res);
					} else {
						reject();
					}
				}
			});
		}
	});
};